'''
Created on Jul 5, 2010

@author: Behrooz Nobakht
'''
from django.db import models
from amscms import settings

class TermManager(models.Manager):
    
    def find_or_create(self, term, lang_code=settings.LANGUAGE_CODE):
        from amscms.dict.models import Term
        from amscms.dict.models import Language
        lang = None
        try:
            lang = Language.objects.get(code=lang_code)
        except:
            return
        if lang is None:
            return
        the_term, created = Term.objects.get_or_create(term=term, language=lang)
        if not created and the_term is None:
            return None
        return the_term
    
    def find_or_create_search_term(self, term, lang_code=settings.LANGUAGE_CODE):
        the_term = self.find_or_create(term, lang_code)
        if the_term is None:
            return None
        if the_term.frequency > 0:
            return the_term
        the_term.save()
        return the_term
    
    def find_popular_terms(self, size=15):
        from amscms.dict.models import Term
        terms = Term.objects.exclude(enabled=False).order_by('-frequency')[0:size]
        return terms
